package com.wf.mock.app.mina;

import java.net.InetSocketAddress;

import lombok.Data;

import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.prefixedstring.PrefixedStringCodecFactory;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.google.common.base.Charsets;
import com.wf.mock.app.mina.app.AppClientHandler;
import com.wf.mock.app.mina.portal.PortalClientHandler;

@Data
public class ConnectorManager {

	public static IoConnector getAppConnector() {
		IoConnector connector = configConnector();
		connector.setHandler(new AppClientHandler());
		return connector;
	}

	public static IoConnector getPortalConnector() {
		IoConnector connector = configConnector();
		connector.setHandler(new PortalClientHandler());
		return connector;
	}

	private static IoConnector configConnector() {
//		IoConnector connector = new NioDatagramConnector();
		IoConnector connector = new NioSocketConnector();

		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(buildCodecFactory()));
		connector.getFilterChain().addLast("executor", new ExecutorFilter());

		connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 20);

		connector.setDefaultRemoteAddress(new InetSocketAddress("182.254.129.174", 9998));
		return connector;
	}

	/**
	 * 构建解码器工厂
	 * 
	 * @return
	 */
	private static ProtocolCodecFactory buildCodecFactory() {
		PrefixedStringCodecFactory codecFactory = new PrefixedStringCodecFactory(Charsets.UTF_8);
		codecFactory.setDecoderMaxDataLength(10000);
		codecFactory.setEncoderMaxDataLength(10000);
		return codecFactory;
	}

}
